from http.server import BaseHTTPRequestHandler
from api.parse import *
import requests, json
class handler(BaseHTTPRequestHandler):
	def do_GET(self):
		self.send_response(415)
		self.send_header('Content-type', 'text/plain')
		self.end_headers()
		self.wfile.write('{"err": 1, "msg": "send POST request instead"}'.encode())
		return
	def do_POST(self):
		self.send_response(200)
		self.send_header('Content-type', 'text/plain')
		self.end_headers()
		if type_post(self) == "json":
			dat = parse_post(self)
			if any(a in dat for a in ('un', 'nk', 'pt', 'tbs', 'fid', 'uss', 'tm', 'reason')):
				yy = dat["reason"]
				if yy == '': yy = '\0'
				res = json.loads(requests.post('https://tieba.baidu.com/pmc/blockid', data = {"day": dat["tm"], "fid": dat["fid"], "tbs": dat["tbs"], "user_name[]": dat["un"], "nick_name[]": dat["nk"], "portrait[]": dat["pt"], "reason": yy, "ie": 'utf-8'}, cookies = {"BDUSS": dat["uss"]}).text)
				if res["errno"] != 0:
					self.wfile.write(f'{{"err": 1, "msg": "failed to ban ID", "dat": "{str(res)}"}}'.encode())
				else:
					self.wfile.write(f'{{"err": 0, "dat": "{str(res)}"}}'.encode())
			else:
				self.wfile.write('{"err": 1, "msg": "argument not satisfied"}'.encode())
		else:
			self.wfile.write('{"err": 1, "msg": "wrong request type"}'.encode())
		return
